package com.cgx.controller;

import com.alibaba.fastjson.JSON;
import com.cgx.utils.ResultVoUtils;
import com.cgx.vo.websocket.MessageVo;
import com.cgx.vo.websocket.MqMessageVo;
import com.cgx.vo.ResultVo;
import com.cgx.websocket.MyWebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenguanxin
 * @date 2021-05-25 23:21
 */
@Controller
@CrossOrigin("*")
@RequestMapping("/websocket")
public class WebsocketController {

    @ResponseBody
    @RequestMapping("/sendMessage")
    public Map<String, ResultVo> sendMessage(@RequestBody MqMessageVo mqMessageVo) {
        String toUserId = mqMessageVo.getToUserId();
        MessageVo message = mqMessageVo.getMessage();
        WebSocketSession session = MyWebSocketHandler.SESSION_MAP.get(toUserId);
        Map<String, ResultVo> result = new HashMap<>();
        ResultVo resultVo = ResultVoUtils.getSuccessResult();
        if (session != null) {
            try {
                session.sendMessage(new TextMessage(JSON.toJSONString(message)));
            } catch (IOException e) {
                e.printStackTrace();
                resultVo = ResultVoUtils.getErrorResult(e.getMessage());
            }
        }
        result.put(message.getMessageId(), resultVo);
        return result;
    }
}
